package org.finesys.common.tenant.service;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import org.finesys.common.core.exception.BusinessException;
import org.finesys.system.api.service.TenantService;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 租户信息合法性校验
 */
public class TenantValidService {

    private final LoadingCache<Long, BusinessException> validTenantCache;

    private static final BusinessException SERVICE_EXCEPTION_NULL = new BusinessException("无异常信息");

    public TenantValidService(TenantService tenantService) {
        this.validTenantCache = Caffeine.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES)
                .expireAfterWrite(1, TimeUnit.MINUTES).build(id -> {
                    try {
                        tenantService.validTenant(id);
                        return SERVICE_EXCEPTION_NULL;
                    } catch (BusinessException e) {
                        return e;
                    }
                });
    }


    public void validTenant(Long id) {
        BusinessException businessException = validTenantCache.get(id);
        if (!Objects.equals(businessException, SERVICE_EXCEPTION_NULL) && Objects.nonNull(businessException)) {
            throw businessException;
        }
    }
}
